package com.wxtech.heartbeat.server.protocol;

import java.sql.SQLException;


import org.apache.log4j.Logger;

import com.wxtech.heartbeat.Context;
import com.wxtech.heartbeat.database.DataManager;
import com.wxtech.heartbeat.model.Device;
import com.wxtech.heartbeat.model.ErrorData;
import com.wxtech.heartbeat.model.HeartBeat;

import io.netty.channel.ChannelHandlerContext;

/**
 * 
字节地址号	字节内容	字节长度
1	心跳信息0x02(心跳标识)	1
2	消息包的长度0x01	1
3	标号0x00	1
4	标号0x01	1
5	设备ID （u64）	8
13	年(u8)	1
14	月(u8)	1
15	日(u8)	1
16	小时(u8)	1
17	分钟(u8)	1
18	秒(u8)	1
19-38	Sim卡号(20个字符char)	20
39-46	表体序列号ID（u64）	8
47	数据帧CRC校验高字节(u8)	1
48	数据帧CRC校验低字节(u8)	1
 *
 */
public class HeartBeatProtocolDecodeResult extends DecodeResult {
	private static Logger logger = Logger.getLogger(HeartBeatProtocolDecodeResult.class);
	//解析好的model对象
	private ErrorData errorData;
	private Device device;
	private HeartBeat heartBeat;
	private boolean isValid;
	
	public ErrorData getErrorData() {
		return errorData;
	}
	public void setErrorData(ErrorData errorData) {
		this.errorData = errorData;
	}
	public Device getDevice() {
		return device;
	}
	public void setDevice(Device device) {
		this.device = device;
	}
	public HeartBeat getHeartBeat() {
		return heartBeat;
	}
	public void setHeartBeat(HeartBeat heartBeat) {
		this.heartBeat = heartBeat;
	}
	public boolean isValid() {
		return isValid;
	}
	public void setValid(boolean isValid) {
		this.isValid = isValid;
	}
	@Override
	public void handler(ChannelHandlerContext ctx) {
		// TODO Auto-generated method stub
		try {
			processBusinessLogic(this);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
//			e.printStackTrace();
			logger.error(e.getMessage(), e);
			throw new RuntimeException(e);
		}
	}
	
	private void processBusinessLogic(HeartBeatProtocolDecodeResult protocol) throws SQLException {
		DataManager dataManager = Context.getDataManager();
		if (protocol.isValid()) {
			Device protocolDevice = protocol.getDevice();
			if (protocolDevice == null) {
				logger.error("device is null");
				return;
			}

			logger.info("check if it is a new device");
			Device device = dataManager.getDevice(protocolDevice.getDevice_id());
			if (device == null) {
				logger.info(protocolDevice.getDevice_id() + " is a new device, saving device data");
				dataManager.addDevice(protocolDevice);
			} else {
				logger.info(device.getDevice_id() + " is an existing device");
			}

			logger.info("save heartbeat data");
			dataManager.addHeartBeat(protocol.getHeartBeat());
		} else {
			logger.warn("heartbeat protocol data is invalid" + protocol.getErrorData());
			logger.info("save ErrorData");
			dataManager.addErrorData(protocol.getErrorData());
		}

	}

}
